package com.wemake.controller;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

/**
 * 处理客户端消息
 * */
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = Logger.getLogger(EchoServerHandler.class.getName());

    // 每当从客户端收到新的数据时，这个方法会在收到消息时被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf bytebuf = (ByteBuf) msg;
        log.info("收到数据：" + bytebuf.toString(StandardCharsets.UTF_8));
    }

    // 数据读取完后被调用
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    // 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 客户端主动断开服务端的链接,关闭流
     * */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info(ctx.channel().remoteAddress() + " 断开连接！");
        ctx.close(); // 关闭流
    }

    /**
     * 客户端主动连接服务端 连接成功时向客户端发送一条信息
     *
     * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info(ctx.channel().remoteAddress() + " 连接成功！");
        ByteBuf response = Unpooled.copiedBuffer(("welcome to " + "homeGuardian tcp" + "!\r\n").getBytes());
        ctx.writeAndFlush(response);
    }
}
